package Utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC的工具类，使用druid数据库连接池实现
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-16-19:42 19:42
 */
public class JDBCUtils {
    private static DataSource dataSource;

    static{

        try {
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取DataSource
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @Description: 返回DataSource对象
     * @Param: []
     * @return: javax.sql.DataSource
     */
    public static DataSource getDataSource(){
        return dataSource;
    }
    /**
     * @Description: 利用数据库连接池创建一个连接对象
     * @Param: []
     * @return: java.sql.Connection
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    /**
     * @Description: 关闭相关的资源
     * @Param: [resultSet, statement, connection]
     * @return: void
     */
    public static void close( ResultSet resultSet,Statement statement,Connection connection){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    /**
     * @Description: close方法的重载，关闭相关的资源
     * @Param: [statement, connection]
     * @return: void
     */
    public static void close(Statement statement,Connection connection){
        close(null,statement,connection);
    }
}
